import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  // eslint-disable-next-line quotes
  // baseURL: "http://192.168.1.22:8100",
     baseURL: window.config.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: -1 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers["token"] = getToken();
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code && res.code == "UNAUTHENTICATED") {
      MessageBox.alert("请登录后访问！", "登录", {
        confirmButtonText: "登录",
        type: "warning"
      }).then(() => {
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
      });
    }
    if (res.code && res.code == "USER_LOCKED_ERROR") {
      MessageBox.alert("请登录后访问！", "登录", {
        confirmButtonText: "登录",
        type: "warning"
      }).then(() => {
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
      });
    }
    return res;
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
